package ch.sfug.util {

	/**
	 * this class will display the current frame rate in a logger output.
	 * basic usage is like this:
	 * <code>
	 * var fps:TextField = new TextField();
	 * addChild(fps);
	 * 
	 * Logger.appendOutput( new LogTextfield(fps), FPSMonitor.LOG );
	 * 
	 * FPSMonitor.start();
	 * </code>
	 * 
	 * note: you can use any LoggerOutput for displaying the fps info.
	 * 
	 * @author mich
	 */
	public class FPSMonitor {
		
		private static var instance:FPSMonitorInner;

		public static var LOG:String = "FPSMonitorLog";

		
		private static function getInstance():FPSMonitorInner {
			if( instance == null ) instance = new FPSMonitorInner(  );
			return instance;
		}
		
		/**
		 * starts the fps monitor
		 */
		public static function start( round:Number = 3 ):void {
			getInstance().start( round );
		}

		
		/**
		 * stops the fps monitor
		 */
		public static function stop(  ):void {
			getInstance().stop();
		}
	}
}

import flash.utils.getTimer;

import ch.sfug.log.Logger;
import ch.sfug.util.EnterFrame;
import ch.sfug.util.FPSMonitor;

/**
 * @author mich
 */
class FPSMonitorInner {
	
	private var oldTime:Number;
	private var i:uint;
	private var round:uint;

	function FPSMonitorInner( ) {
	}

	private function updateMonitor():void {
		var newTime:Number = getTimer();
		var delta:Number = newTime - oldTime;
		var fps:Number = Math.round( 1000 * round / delta );
		Logger.clear( FPSMonitor.LOG );
		Logger.log( "fps: " + fps, FPSMonitor.LOG );
		oldTime = newTime;
	}
	
	private function update():void {
		if( i >= round ) {
			i = 1;
			updateMonitor();
		} else {
			i++;
		}
	}

	
	
	internal function start( round:uint ):void {
		this.round = round;
		i = 1;
		oldTime = getTimer();
		EnterFrame.add( update );
	}

	internal function stop():void {
		EnterFrame.remove( update );
	}
}
